package com.example.library_common.album.ui

import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.text.TextUtils
import android.view.LayoutInflater
import android.view.View
import android.widget.CheckBox
import android.widget.TextView
import androidx.appcompat.widget.Toolbar
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.PagerSnapHelper
import androidx.recyclerview.widget.RecyclerView
import com.example.su_shi_tan_bas_lib.album.constant.FILE_SCAN
import com.example.library_common.album.utils.ALBUM_SELECT_REFRESH
import com.example.su_shi_tan_bas_lib.R
import com.example.su_shi_tan_bas_lib.adapter.JssBaseViewHolder
import com.example.su_shi_tan_bas_lib.album.bean.AlbumFile
import com.example.su_shi_tan_bas_lib.album.bean.FunctionBean
import com.example.su_shi_tan_bas_lib.album.interfaces.AlbumPanelNode
import com.example.su_shi_tan_bas_lib.album.ui.AlbumPreviewFooterListFragment
import com.example.su_shi_tan_bas_lib.album.utils.GalleryDecoration
import com.example.su_shi_tan_bas_lib.base.SimpleListFragment
import com.example.su_shi_tan_bas_lib.bean.CommonBean
import com.example.su_shi_tan_bas_lib.utils.even.MessageWrap
import ikidou.reflect.TypeBuilder
import org.greenrobot.eventbus.EventBus
import java.io.File
import java.lang.reflect.Type


class AlbumPreviewFragment : SimpleListFragment<AlbumFile>() {

    companion object {
        fun newInstance() = AlbumPreviewFragment()
    }

    private lateinit var mToolbar: Toolbar

    private lateinit var mCheckItemTextView: TextView

    private lateinit var editorImg: TextView

    private lateinit var mCheckBox: CheckBox

    private val mPreviewFooterListFragment = AlbumPreviewFooterListFragment()

    private var maxSelectedCount = FunctionBean.MIN_SELECT_COUNT

    private var funBean: FunctionBean? = null

    private val mCheckItem = mutableListOf<AlbumFile>()

    private var currentIndex = 0

    private var unCheckItemCount = 0

//    private var mChangedListener: SelectedChangedListener? = null
//    fun setChangedListener(mChangedListener: SelectedChangedListener) {
//        this.mChangedListener = mChangedListener
//    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        mSuperBackPressedSupport = false
        isInitialRefresh = false
        isEnableLoadMore = false
        isAlwaysRefresh = false
//        isAddDividerItemDecoration = false

        val parentFragment = parentFragment

        if (parentFragment is AlbumPanelNode) {
            funBean = (parentFragment as AlbumPanelNode).functionBean
            maxSelectedCount = funBean?.selectCount ?: maxSelectedCount
            mCheckItem.addAll(funBean?.checkedFiles ?: emptyList())
            mData.addAll(mCheckItem)
            mPreviewFooterListFragment.addData(mData)
        }
    }

    fun setCurrentIndex(index: Int) {

        currentIndex = if (index >= 0 && index < mCheckItem.size) index else 0

        mPreviewFooterListFragment.setCurrentIndex(currentIndex)
    }

    override fun addItemDecoration(): RecyclerView.ItemDecoration {
        val galleryDecoration = GalleryDecoration()
        galleryDecoration.setIndexIndicator { index, itemCount ->
            mToolbar.title = _mActivity.getString(
                R.string.album_preview_title,
                "${index + 1}/${itemCount}"
            )
            currentIndex = index

            mCheckBox.isChecked = mCheckItem[index].isChecked

            mPreviewFooterListFragment.setCurrentIndexCheck(currentIndex, mCheckBox.isChecked)

        }
        return galleryDecoration
    }

    override fun initView(view: View) {
        super.initView(view)
        mSwipeRefreshLayout.isEnabled = false
        initHeaderView()
        initContentFrameView()

        mRecyclerView.scrollToPosition(currentIndex)

        val snapHelper = PagerSnapHelper()
        mRecyclerView.onFlingListener = null
        snapHelper.attachToRecyclerView(mRecyclerView)

        mPreviewFooterListFragment.setListItemClick(object :
            AlbumPreviewFooterListFragment.PreviewFooterListItemClick {
            override fun onPreviewFooterListItemClick(item: AlbumFile) {
                mCheckItem.forEachIndexed { index, albumFile ->
                    if (item == albumFile) {

                        currentIndex = index

                        mToolbar.title = _mActivity.getString(
                            R.string.album_preview_title,
                            "${index + 1}/${mCheckItem.size}"
                        )
                        mRecyclerView.scrollToPosition(currentIndex)
                    }
                }
            }

        })
    }

    private fun initContentFrameView() {
        content_frame.removeAllViews()
        content_frame.visibility = View.VISIBLE
        LayoutInflater.from(_mActivity)
            .inflate(R.layout.fragment_album_preview_footer, content_frame)

        loadRootFragment(R.id.selected_List, mPreviewFooterListFragment)

        editorImg = content_frame.findViewById(R.id.editorImg)

        mCheckBox = content_frame.findViewById(R.id.mCheckBox)

        editorImg.setOnClickListener {
            val newInstance =
                EditorImgFragment.newInstance(mCheckItem[currentIndex])
            newInstance.setResultListener(object : EditorImgFragment.EditorResultListener {
                override fun onResult(mAlbumFile: AlbumFile) {
                    mCheckItem[currentIndex] = mAlbumFile

//                    funBean?.checkedFiles?.clear()
//                    funBean?.checkedFiles?.addAll(mCheckItem)

                    mAdapter.notifyItemChanged(currentIndex)

                    if (!TextUtils.isEmpty(mAlbumFile.editorPath)) {
                        sendSysBroadcast(mAlbumFile.editorPath)
                    }


                }
            })
            start(newInstance)
        }

        mCheckBox.setOnClickListener {
            mCheckItem[currentIndex].isChecked = !mCheckItem[currentIndex].isChecked
            if (!mCheckItem[currentIndex].isChecked) {
                unCheckItemCount++
            } else {
                unCheckItemCount--
            }
            mCheckItemTextView.text =
                _mActivity.getString(
                    R.string.album_selector,
                    "${mCheckItem.size - unCheckItemCount}/${maxSelectedCount}"
                )
            mPreviewFooterListFragment.setCurrentIndexCheck(currentIndex, mCheckBox.isChecked)
        }

        mCheckBox.isChecked = mCheckItem[currentIndex].isChecked
    }

    private fun sendSysBroadcast(temp: String?) {
        val contentFileUri: Uri = Uri.fromFile(File(temp))
        val mediaScanIntent =
            Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, contentFileUri)
        _mActivity.sendBroadcast(mediaScanIntent)

        val local =
            Intent(FILE_SCAN)
        _mActivity.sendBroadcast(local)
    }

    private fun initHeaderView() {
        mHeader.removeAllViews()
        addHeader(R.layout.fragment_album_preview_header)
        mToolbar = mHeader.findViewById(R.id.mToolbar)
        mCheckItemTextView = mHeader.findViewById(R.id.mCheckItemTextView)

        mCheckItemTextView.text =
            _mActivity.getString(
                R.string.album_selector,
                "${mCheckItem.size}/${maxSelectedCount}"
            )

        mToolbar.title = _mActivity.getString(
            R.string.album_preview_title,
            "${currentIndex + 1}/${mCheckItem.size}"
        )

        mCheckItemTextView.setOnClickListener {

            mCheckItem.forEach {
                if (!TextUtils.isEmpty(it.editorPath)) {
                    it.path = it.editorPath
                }
            }

            val ls = mutableListOf<AlbumFile>()
            if (unCheckItemCount > 0) {

                mCheckItem.forEach {
                    if (it.isChecked) {
                        ls.add(it)
                    }
                }
                funBean?.checkedFiles?.clear()
                funBean?.checkedFiles?.addAll(ls)
                EventBus.getDefault().post(MessageWrap.getInstance(ALBUM_SELECT_REFRESH))
//            mChangedListener?.onChanged()
            }

            if (ls.isEmpty()){
                pop()
                return@setOnClickListener
            }
            funBean?.successCallback?.onSuccess(mCheckItem)

            val parentFragment = parentFragment

            if (parentFragment is AlbumPanelNode) {

                parentFragment.finish()
            }
        }

        mToolbar.setNavigationOnClickListener {
            onBackPressedSupport()
        }
    }

    override fun getItemLayout() = R.layout.fragment_album_preview_item

    override fun convertItem(helper: JssBaseViewHolder?, item: AlbumFile?) {
        val temp = if (TextUtils.isEmpty(item?.editorPath)) item?.path else item?.editorPath
        helper?.setImageLocalUrl(R.id.mPhotoView, temp, R.drawable.img_erros_bg_rect)
    }


    override fun getLayoutManager() =
        LinearLayoutManager(_mActivity, LinearLayoutManager.HORIZONTAL, false)

    override fun getListType(): Type = TypeBuilder.newInstance(CommonBean::class.java)
        .endSubType().build()

    override fun netRequest() {

    }

    override fun onRefresh() {

    }

    override fun onDestroy() {
        super.onDestroy()
        if (unCheckItemCount > 0) {
            val ls = mutableListOf<AlbumFile>()
            mCheckItem.forEach {
                if (it.isChecked) {
                    ls.add(it)
                }
            }
            funBean?.checkedFiles?.clear()
            funBean?.checkedFiles?.addAll(ls)
            EventBus.getDefault().post(MessageWrap.getInstance(ALBUM_SELECT_REFRESH))
//            mChangedListener?.onChanged()
        }

    }

//    interface SelectedChangedListener {
//        fun onChanged()
//    }
}